package com.hk.uploadservice.controller;

import com.hk.commons.CommonResult;
import com.hk.model.vo.UploadImage;
import com.hk.model.vo.UploadImageVO;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Author: aerfazhe
 * @Date: 2021/7/2 9:46
 * @Statement: 上传图片
 */
@RestController
@RequestMapping("/upload")
public class UploadImageController {

//    todo 返回图片访问地址为localhost，需要修改，不能回显 (已解决)
    @PostMapping("/uploadImage")
    public UploadImageVO uploadImage(HttpServletRequest req, HttpServletResponse resp, MultipartFile file) throws IOException {
        //        获取当前请求的协议、IP、端口
//        String url = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort();
        String url = req.getScheme()+"://"+"img.hk.com";
//        当前时间设置模板
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String date = format.format(new Date());
//        图片存放路径
        String imageFileUrl = "/img"+"/"+date+"/";
//        存放在固定盘符项目img文件夹中
        String uploadPath = "F:/IDEA/huakang7-company/hk-upload/upload-service/src/main/resources/static"+imageFileUrl;
//        存放在Tomcat 编译后路径
        String readadPath = req.getSession().getServletContext().getRealPath(imageFileUrl);
        File file1 = new File(uploadPath);
        File file2 = new File(readadPath);
//        判断该路径是否存在或创建
        if (!file1.exists()) {
            file1.mkdirs();
        }
        if (!file2.exists()) {
            file2.mkdirs();
        }
        System.out.println("上传文件到："+uploadPath);
        System.out.println("读取文件到："+readadPath);
        String fileName = file.getOriginalFilename();
        //                    防止图片名称重复
        String substring = UUID.randomUUID().toString().replace("-", "").substring(1,8);
        substring +="-"+fileName;
        String img = url+imageFileUrl+substring;
//        上传到Tomcat编译后路径
        uploadImage(file.getInputStream(),new File(readadPath, substring));
//        上传图片
        file.transferTo(new File(uploadPath,substring));
//        延迟一秒返回结果
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (fileName != null) {
            UploadImage uploadImage = new UploadImage(img, substring);
            UploadImageVO uploadImageVO = CommonResult.successUploadImgVO(uploadImage);
            return uploadImageVO;
        } else {
            UploadImage uploadImage = new UploadImage(img, substring);
            UploadImageVO uploadImageVO = CommonResult.errorUploadImgVO(uploadImage);
            return uploadImageVO;
        }
    }


    /**
     * 图片上传
     * @param destination
     * @throws IOException
     */
    public void uploadImage(InputStream inputStream,File destination) throws IOException {
        FileOutputStream outputStream = null;
        try {
            byte[] bytes = new byte[1024];
            int len = 0;
            outputStream = new FileOutputStream(destination);
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes,0,len);
            }
        } finally {
            if (outputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
        }
    }

}
